package com.yan.hibernate_ann.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

	private static SessionFactory FACTORY = buildSessionFactory();
	
	private static SessionFactory buildSessionFactory(){
		try {
			Configuration cfg = new Configuration().configure();
			/*
			 * 
			 //以下这两句就是4.1的用法
			ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
					.applySettings(cfg.getProperties()).buildServiceRegistry();
			*/
			//以下这两句就是4.3.5的新用法
			ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
			.applySettings(cfg.getProperties()).build();
			SessionFactory factory = cfg.buildSessionFactory(serviceRegistry);
			return factory;
		} catch (HibernateException e) {
			System.err.println("Initial SessionFactory creation failed." + e);
		    throw new ExceptionInInitializerError(e);
		}
	}
	
	public static SessionFactory getSessionFactory(){
		return FACTORY;
	}
	
	public static Session openSession(){
		return FACTORY.openSession();
	}
	
	public static void closeSession(Session session){
		if(session != null) {
			session.close();
			FACTORY.close();
		}
	}
}
